package com.ke.searchhouse.service.impl;

import com.ke.searchhouse.constant.RedisKeyConstant;
import com.ke.searchhouse.service.ISmsService;
import com.ke.searchhouse.util.ServiceResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class SmsServiceImpl implements ISmsService {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;


    @Override
    public ServiceResult<String> sendSms(String telephone) {
        String key = RedisKeyConstant.SMS_CODE_KEY + telephone;

        String result = redisTemplate.opsForValue().get(key);

        if (result != null) {
            return new ServiceResult<>(false, "请求过于频繁,请稍后再试");
        }

        redisTemplate.opsForValue().set(key, "123456", 60, TimeUnit.SECONDS);

        return ServiceResult.success();
    }

    @Override
    public String getSmsCode(String telephone) {
        String key = RedisKeyConstant.SMS_CODE_KEY + telephone;

        String result = redisTemplate.opsForValue().get(key);

        return result;
    }

    @Override
    public void remove(String telephone) {
        String key = RedisKeyConstant.SMS_CODE_KEY + telephone;

        redisTemplate.delete(key);
    }
}
